<?php

namespace app\controller;


//用户好友控制器
use app\service\UserFriendService;
use support\Response;
use think\Exception;
use think\facade\Db;

class UserFriendController extends Base
{


    //获取好友列表
    public function index(): Response
    {

        try {
            $res = (new UserFriendService())->list($this->user_id);
        } catch (Exception $e) {
            return $this->fail("数据库异常");
        }


        return $this->json($res);

    }

    //添加好友
    public function add(): Response
    {
        $friend_id = $this->request->post('friend_id', 0);
        $remarks = $this->request->post('remarks', '加个好友吧');
        if ($friend_id == 0) {
            return $this->fail('参数错误');
        }

        Db::startTrans();
        try {
            $res = (new UserFriendService())->add($this->user_id, $friend_id, $remarks);
            if ($res['code'] == 0) {
                Db::rollBack();
            } else {
                Db::commit();
            }
        } catch (Exception $e) {
            Db::rollBack();
            return $this->fail("数据库异常");
        }

        return $this->json($res);
    }

    //验证好友
    public function verify(): Response
    {
        $friend_id = $this->request->post('friend_id', 0);
        $state = $this->request->post('state', 0);
        if ($friend_id == 0) {
            return $this->fail('参数错误');
        }

        Db::startTrans();
        try {
            $res = (new UserFriendService())->verify($this->user_id, $friend_id, $state);
            if ($res['code'] == 0) {
                Db::rollBack();
            } else {
                Db::commit();
            }
        } catch (Exception $e) {
            Db::rollBack();
            return $this->fail("数据库异常");
        }

        return $this->json($res);


    }



}